package com.tiancai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancai.pojo.dto.CategoryDto;
import com.tiancai.pojo.po.Category;
import com.tiancai.pojo.po.Work;
import com.tiancai.pojo.vo.WorkDetailVo;
import com.tiancai.result.Result;
import com.tiancai.service.ICategoryService;
import com.tiancai.service.IWorkService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tiancai
 * @since 2025-04-24
 */
@RestController
@RequestMapping("/category")
@Tag(name = "分类管理")
@Slf4j
@CrossOrigin
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IWorkService workService;
    @PostMapping("/add")
    @Operation(summary = "新增分类")
    public Result<Category> add(@RequestParam String name){
        Category category = Category.builder()
                .name(name)
                .build();
        categoryService.save(category);
        return Result.success(category);
    }
    @GetMapping("/list")
    @Operation(summary = "查询分类列表")
    public Result<List<Category>> list(){
        return Result.success(categoryService.list());
    }
    @GetMapping("/getCategoryById/{id}")
    @Operation(summary = "根据id查询分类")
    public Result<Category> getCategoryById(@PathVariable Long id){
        return Result.success(categoryService.getById(id));
    }
    @PutMapping("/update")
    @Operation(summary = "修改分类")
    public Result<Category> update(@RequestBody CategoryDto categoryDto){
        Category category = Category.builder()
                .id(categoryDto.getId())
                .name(categoryDto.getName())
                .build();
        categoryService.updateById(category);
        return Result.success();
    }
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除分类")
    public Result<Category> delete(@PathVariable Long id){
        //如果分类下没有作品直接删除，如果分类下有作品则不能删除
        //查看作品表，如果有该分类id的数据，则不能删除
        if (workService.count(new QueryWrapper<Work>().eq("category_id", id)) > 0) {
            return Result.error("该分类下有作品，不能删除");
        }else {
            categoryService.removeById(id);
            return Result.success();
        }
    }
    //查询作品列表
    @GetMapping("/getWorkByCategoryId/{id}")
    @Operation(summary = "根据分类id查询作品详情列表")

    public Result<List<Work>> getWorkByCategoryId(@PathVariable Long id){
        return Result.success(workService.list(new QueryWrapper<Work>().eq("category_id", id)));
    }
}
